﻿using Manox.Libs.Foundation;
using Manox.Libs.Networking;


namespace Manox.Libs.ODB
{
    /// <summary>
    /// ODB Synchronization message translator.
    /// </summary>
    public class ODBSynchronizationMessageTranslator : TypeTranslator
    {
        /// <summary>Singleton.</summary>
        public static readonly ODBSynchronizationMessageTranslator Instance = new ODBSynchronizationMessageTranslator();

        
        /// <summary>
        /// Constructor.
        /// </summary>
        public ODBSynchronizationMessageTranslator()
        {
            this.RegisterType<ItemAddedEventArgs>();
            this.RegisterType<ItemWithPropertiesAddedEventArgs>();
            this.RegisterType<ObjectDatabasePropertyValueChangedEventArgs>();
            this.RegisterType<ObjectDatabaseObjectPropertyValueChangedEventArgs>();
            this.RegisterType<ObjectDatabaseListChangedEventArgs>();
            this.RegisterType<ODBSynchronizerRequestEventArgs>();            
        }
    }

    /// <summary>
    /// ODB Synchronization message.
    /// </summary>
    public class ODBSynchronizationMessage : NetworkMessage
    {
        /// <summary>Event args.</summary>
        public ObjectDatabaseEventArgs EventArgs;


        /// <summary>
        /// Serialize.
        /// </summary>
        /// <param name="writer"></param>
        public override void Serialize(SerializeWriter writer)
        {
            base.Serialize(writer);

            writer.Write(ODBSynchronizationMessageTranslator.Instance.GetTypeId(this.EventArgs.GetType()));

            this.EventArgs.Serialize(writer);
        }

        /// <summary>
        /// Deserialize.
        /// </summary>
        /// <param name="reader"></param>
        public override void Deserialize(SerializeReader reader)
        {
            base.Deserialize(reader);

            this.EventArgs = 
                ODBSynchronizationMessageTranslator.Instance.GetInstance(reader.ReadByte()) as ObjectDatabaseEventArgs;

            if (this.EventArgs != null)
                this.EventArgs.Deserialize(reader);
        }       
    }
}
